package servlet;

import demo.User;
import listener.a;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Properties;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 登录界面 进行Session 的存储，以及Cookie存储以进行登陆的验证
 *
 */
public class LoginServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws javax.servlet.ServletException, IOException {

        //接收
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        //session 存储
        HttpSession session = req.getSession();
        session.setAttribute("name",name);
        session.setAttribute("password",password);


            //Cookie 把姓名和密码 存入cookie里面
            Cookie cookie = new Cookie(URLEncoder.encode(name,"UTF-8"),password);
            resp.addCookie(cookie);




        //获取存储信息
        Properties properties = new Properties();
        a a = new a();
        a.test();
        File file = new File(a.filePath);
        properties.load(new BufferedReader(new FileReader(file)));
        //读取一共有几条信息
        int num = Integer.parseInt(properties.getProperty("num"));
        //建立集合存储信息
        ArrayList<User> list_user = new ArrayList<>();
        //分别循环出信息
        for (int user_i = 1;user_i<= num ; user_i++){
            User user = new User();
            //通过字符串拼接，完成信息的查询
            String name_prop = "name"+Integer.toString(user_i);
            String password_prop = "password"+Integer.toString(user_i);
            //读取每一个用户信息，设置到user对象里
            user.setName(properties.getProperty(name_prop));
            user.setPassword(properties.getProperty(password_prop));
            //添加到list里
            list_user.add(user);
        }


        //循环判断标识符 判断是否登陆上去
        Boolean demo_user = false;
        //循环查找账户密码
        for (User user : list_user){
            //判断登录账户密码是否正正确
            if(user.getName().equals(name) && user.getPassword().equals(password)){
                 //重定向
                resp.sendRedirect(req.getContextPath()+"/display.jsp");
                demo_user = true;
            }

        }
//        提示错误信息
        if (demo_user.equals(false)){
            //存储错误提示
            session.setAttribute("logininf",false);
            //转发
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }







    }

    protected void doGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws javax.servlet.ServletException, IOException {


    }
}
